<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="产品编码" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入产品编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 工具栏 -->
    <el-row :gutter="10" class="mb8">
      <!-- 使用权限控制显示按钮 -->
      <el-col :span="1.5" v-if="pageActions.canAdd">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['qep:product:add']"
        >新增</el-button>
      </el-col>
      
      <el-col :span="1.5" v-if="pageActions.canEdit">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['qep:product:edit']"
        >修改</el-button>
      </el-col>
      
      <el-col :span="1.5" v-if="pageActions.canDelete">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['qep:product:remove']"
        >删除</el-button>
      </el-col>
      
      <el-col :span="1.5" v-if="pageActions.canExport">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['qep:product:export']"
        >导出</el-button>
      </el-col>
      
      <!-- 只有质量管理员及以上才能导入 -->
      <el-col :span="1.5" v-if="isQualityMgr && pageActions.canImport">
        <el-button
          type="info"
          plain
          icon="Upload"
          @click="handleImport"
          v-hasPermi="['qep:product:import']"
        >导入</el-button>
      </el-col>
      
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange">
      <!-- 只有管理员和质量管理员才显示选择框 -->
      <el-table-column type="selection" width="55" align="center" v-if="permissions.canManageProduct" />
      
      <el-table-column label="产品编码" align="center" prop="code" />
      <el-table-column label="产品名称" align="center" prop="name" />
      <el-table-column label="产品分类" align="center" prop="categoryName" />
      <el-table-column label="产品规格" align="center" prop="specification" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '正常' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <!-- 动态渲染操作按钮 -->
          <template v-for="action in tableActions" :key="action.action">
            <el-button 
              :link="true" 
              :type="action.type" 
              :icon="action.icon" 
              @click="handleAction(action.action, scope.row)"
              v-hasPermi="[action.permission]"
            >
              {{ action.label }}
            </el-button>
          </template>
          
          <!-- 更多操作下拉菜单 (只有质量管理员可见) -->
          <el-dropdown v-if="permissions.canManageProduct">
            <el-button link type="primary">
              更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="handleProcess(scope.row)" icon="Connection">工序配置</el-dropdown-item>
                <el-dropdown-item @click="handleStandard(scope.row)" icon="Document">质量标准</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 用户角色信息提示 -->
    <el-card class="role-info-card" style="margin-top: 20px;" v-if="!isAdmin">
      <template #header>
        <span>当前用户权限信息</span>
      </template>
      <el-row>
        <el-col :span="8">
          <el-tag type="primary" v-if="isAdmin">系统管理员</el-tag>
          <el-tag type="success" v-else-if="isQualityMgr">质量管理员</el-tag>
          <el-tag type="warning" v-else-if="isInsp">检验员</el-tag>
        </el-col>
        <el-col :span="16">
          <el-text class="mx-1" size="small">
            <template v-if="isQualityMgr">
              您可以管理产品信息、创建检验任务、分析质量数据等
            </template>
            <template v-else-if="isInsp">
              您可以查看产品信息、录入检验数据、查询质量数据等
            </template>
          </el-text>
        </el-col>
      </el-row>
    </el-card>

    <!-- 添加或修改产品信息对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <!-- 对话框内容 -->
      <el-form ref="productRef" :model="form" :rules="rules" label-width="100px">
        <!-- 表单内容... -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { listProduct, getProduct, delProduct, addProduct, updateProduct } from '@/api/qep/product'
import { usePagePermission, useTableActions } from '@/mixins/permission'

// 使用权限管理组合函数
const { pageActions, permissions } = usePagePermission('product')
const { tableActions } = useTableActions('product')

// 角色判断
const isAdmin = computed(() => permissions.value.canManageUser)
const isQualityMgr = computed(() => permissions.value.canManageProduct)
const isInsp = computed(() => permissions.value.canViewProduct)

// 数据定义
const productList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  code: null,
  name: null
})

// 表单数据
const form = reactive({})

// 表单验证规则
const rules = reactive({
  code: [
    { required: true, message: "产品编码不能为空", trigger: "blur" }
  ],
  name: [
    { required: true, message: "产品名称不能为空", trigger: "blur" }
  ]
})

/** 查询产品信息列表 */
function getList() {
  loading.value = true
  listProduct(queryParams).then(response => {
    productList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/** 取消按钮 */
function cancel() {
  open.value = false
  reset()
}

/** 表单重置 */
function reset() {
  Object.assign(form, {
    id: null,
    code: null,
    name: null,
    status: 1
  })
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 10,
    code: null,
    name: null
  })
  handleQuery()
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加产品信息"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const id = row.id || ids.value
  getProduct(id).then(response => {
    Object.assign(form, response.data)
    open.value = true
    title.value = "修改产品信息"
  })
}

/** 统一的操作处理方法 */
function handleAction(action, row) {
  switch (action) {
    case 'edit':
      handleUpdate(row)
      break
    case 'delete':
      handleDelete(row)
      break
    case 'view':
      handleDetail(row)
      break
  }
}

/** 删除按钮操作 */
function handleDelete(row) {
  const productIds = row.id || ids.value
  proxy.$modal.confirm('是否确认删除产品信息编号为"' + productIds + '"的数据项？').then(function() {
    return delProduct(productIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 查看详情 */
function handleDetail(row) {
  // 跳转到详情页面或弹出详情对话框
  this.$router.push({ path: '/product/detail', query: { id: row.id } })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('qep/product/export', {
    ...queryParams
  }, `product_${new Date().getTime()}.xlsx`)
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["productRef"].validate(valid => {
    if (valid) {
      if (form.id != null) {
        updateProduct(form).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addProduct(form).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

// 组件挂载时获取数据
onMounted(() => {
  getList()
})
</script>

<style scoped>
.role-info-card {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.role-info-card .el-card__header {
  background-color: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
}
</style> 